<?php

/**
 * This is the model class for table "{{category}}".
 *
 * The followings are the available columns in table '{{category}}':
 * @property string $CatID
 * @property string $ParentID
 * @property string $Title
 * @property string $Brief
 * @property string $AddTime
 * @property string $Sorting
 * @property string $Status
 */
class CategoryArticleModel extends BaseModel
{
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{category_article}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('Title', 'required'),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('ParentID, Brief, Sorting', 'safe'),
			array('ParentID, Title, Brief, AddTime, Sorting, Status', 'safe', 'on'=>'admin'),
			array('CatID, ParentID, Title, Brief, AddTime, Sorting, Status', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'CatID' => 'ID',
			'ParentID' => '父ID',
			'Title' => '标题',
			'Brief' => '简介',
			'AddTime' => '添加时间',
			'Sorting' => '排序',
			'Status' => '是否可用',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('CatID',$this->CatID,true);
		$criteria->compare('ParentID',$this->ParentID,true);
		$criteria->compare('Title',$this->Title,true);
		$criteria->compare('Brief',$this->Brief,true);
		$criteria->compare('AddTime',$this->AddTime,true);
		$criteria->compare('Sorting',$this->Sorting,true);
		$criteria->compare('Status',$this->Status,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	public function createSearchCriteria()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('CatID',$this->CatID,true);
		$criteria->compare('ParentID',$this->ParentID,true);
		$criteria->compare('Title',$this->Title,true);
		$criteria->compare('Brief',$this->Brief,true);
		$criteria->compare('AddTime',$this->AddTime,true);
		$criteria->compare('Sorting',$this->Sorting,true);
		$criteria->compare('Status',$this->Status,true);

		return $criteria;
	}


	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return CategoryArticleModel the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	public function beforeSave(){
		if($this->isNewRecord){
			$this->AddTime = time();
		}
		return true;
	}

	/**
	 * 取所有的数据然后缓存，其它的函数都是先通过这个函数来取，然后再处理
	 * @param  [type] $intCatID [description]
	 * @return [type]           [description]
	 */
	public static function getList($bloIsCache = true){
		$strKey = "CategoryArticleModel_getList";
		$arrCache = yii::app()->cache->get($strKey);
        if($bloIsCache && $arrCache !== false){
            return $arrCache;
        }

        $arrCache = array();
        $objCriteria = BaseModel::getC(array('Status' => 1));
        $objCriteria->order = 'Sorting desc,CatID asc';
        $objModels = self::model()->findAll($objCriteria);
        foreach ($objModels as $key => $objModel) {
        	$arrCache[$objModel->CatID] = $objModel->attributes;
        }
        
        yii::app()->cache->set($strKey, $arrCache, 600);
        return $arrCache;		
	}

	public function afterSave(){
		parent::afterSave();
		self::getList(false);
	}
	public function afterDelete(){
		parent::afterDelete();
		self::getList(false);
	}

	/**
	 * 通过catid来获取它底下的所有的数据，包括它本身
	 * $intLayer 取几层的数据  默认false所有的都取出来
	 * @return [type] [description]
	 */
	public static function getListCatID($intCatID, $intLayer = false){
    	$arrDatas = self::getList();
    	$arrResult[$intCatID] = $arrDatas[$intCatID];
    	$arrResult[$intCatID]['Layer'] = 1;  //默认这个是第一层的数据
    	foreach($arrDatas as $CatID => $arrData){
    		if($intLayer){
    			//有这样的key，且它小于该有的层数就可以
	    		if(array_key_exists($arrData['ParentID'], $arrResult) && $arrResult[$arrData['ParentID']]['Layer'] < $intLayer){
	    			$arrResult[$CatID] = $arrData;
	    			$arrResult[$CatID]['Layer'] = $arrResult[$arrData['ParentID']]['Layer'] + 1;
	    		}    			
    		}else{
	    		if(array_key_exists($arrData['ParentID'], $arrResult)){
	    			$arrResult[$CatID] = $arrData;
	    		}
    		}
    	}
    	return $arrResult;
	}

	/**
	 * 获取所有的分类，最多获取两层的数据
	 * $intLayer定义了第几层  如果是第1层则获取所有第一层的数据
	 * @param  boolean $intLayer [description]
	 * @return [type]            [description]
	 */
	public static function  getListMenu($intLayer = 1){
		$arrDatas = self::getList();
		$arrResult = array();
    	foreach($arrDatas as $CatID => $arrData){
			//有这样的key，且它小于该有的层数就可以
			if($arrData['ParentID'] == 0){
				$arrResult[$CatID] = $arrData;
				$arrResult[$CatID]['Layer'] = 1;
			}else{
	    		if(array_key_exists($arrData['ParentID'], $arrResult) && $arrResult[$arrData['ParentID']]['Layer'] < $intLayer){
	    			$arrResult[$arrData['ParentID']]['data'][$CatID] = $arrData;
	    			$arrResult[$arrData['ParentID']]['data'][$CatID]['Layer'] = $arrResult[$arrData['ParentID']]['Layer'] + 1;
	    		} 
			}  
    	}
    	return $arrResult;		
	}

	/**
	 * 获取全部树型的数据 数组形式呈现
	 * 形式是catid => Title
	 * @return [type] [description]
	 */
	public static function getListTree(){
        Tree::$arrData = self::getList();
        return Tree::getArrData();
	}

	/**
	 * 获取所有的数据，除了标题 按数组方式呈现
	 * 形式是catid => array()
	 * @return [type] [description]
	 */
	public static function getListTreeArr(){
		$arrResult = array();
		$arrTree = self::getListTree();
		$arrDatas = self::getList();
		foreach ($arrTree as $key => $value) {
			$arrResult[$key] = $arrDatas[$key];
			$arrResult[$key]['treetitle'] = $value;
		}
		return $arrResult;
	}
	/**
	 * 状态
	 * @return [type] [description]
	 */
	public static function getStatusHtml($mixData = false){
		$arrData = array(
			0 => '不可用',
			1 => '可用',			
		);
		if($mixData !== false){
			return $arrData[$mixData];
		}else{
			return $arrData;
		}
	}

    /**
     * 根据栏目ID删除
     * @param type $catid 栏目ID
     * @return type
     */
    public static function deleteCategoryByPk($catid) {
        if (empty($catid)) {
            return $catid;
        }
        $model = self::model()->findByPk($catid);
        if (empty($model)) {
            return false;
        }
        $info = $model->attributes;
        //检查是否有子栏目
        $childid = self::getStrChildid($info['CatID']);
        if (empty($childid)) {
            return $model->delete();
        }

        $bloResult = self::model()->deleteAll(self::model()->where(array('CatID' => array('IN', $childid))));
        //删除了数据之后更新缓存
        self::getList(false);
        return $bloResult;
    }

    /**
     * 获取子栏目ID列表,,用于删除的时候跟前台需要获取相关的分类的时候用得以
     * 取其底下的所有的1,2,3格式
     * @param type $catid 栏目id
     * @return string 返回栏目子列表，以逗号隔开
     */
    public static function getStrChildid($catid) {
        //栏目数据
    	$arrDatas = self::getList();
        $arrchildid = $catid;
        foreach ($arrDatas as $id => $cat) {
            if ($cat['ParentID'] && $id != $catid && $cat['ParentID'] == $catid) {
                $arrchildid .= ',' . self::getStrChildid($id);
            }
        }
        return $arrchildid;
    }
    /**
     * 获取子栏目ID列表,,用于删除的时候跟前台需要获取相关的分类的时候用得以
     * 取其底下的所有的array(1,2,3)格式
     * @param type $catid 栏目id
     * @return string 返回栏目子列表，以逗号隔开
     */
    public static function getArrChildid($catid) {
        //栏目数据
    	$str = self::getStrChildid($catid);
    	return explode(',', $str);
    }
    /**
     * 根据catid取其单条信息
     * 可根据某字段来取
     * @param  [type] $intCatID [description]
     * @return [type]           [description]
     */
    public static function getDataDetail($intCatID, $strField = ''){
    	$arrData = self::getList();
    	if($strField){
    		return $arrData[$intCatID][$strField];
    	}
    	return $arrData[$intCatID];
    }

    /**
     * 取得所有的父ID为0的
     * 根据某个字段来取值。。。。
     * @return [type] [description]
     */
    public static function getParentList($strField = ''){
    	$arrResult = array();
    	$arrDatas = self::getList();
    	foreach ($arrDatas as $key => $arrData) {
    		if($arrData['ParentID'] == 0){
    			if($strField){
    				$arrResult[$key] = $arrData[$strField];
    			}else{
    				$arrResult[$key] = $arrData;
    			}
    		}
    	}
    	return $arrResult;
    }


}
